package net.xdclass.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.xdclass.model.LoginUser;

import java.util.Date;

public class JWTUtils {

    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7 * 10;

    private static final String SECRET = "xdclass.net666";

    private static final String TOKEN_PREFIX = "xdclass1024shop";

    private static final String SUBJECT = "xdclass";

    public static String generateJSONWebToken(LoginUser user) {
        long userId = user.getId();
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("id", userId)
                .claim("name", user.getName())
                .claim("mail", user.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

        token = TOKEN_PREFIX + token;

        return token;
    }

    public static Claims checkJWT(String token) {
        try {
            token = token.replace(TOKEN_PREFIX, "");
            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
